#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>

int main(int argc, char *argv[])
{
    int sock[2];
    int pid;
    int i;
    static char buf[128];
    if (socketpair(PF_UNIX, SOCK_STREAM, 0, sock) < 0)
    {
        perror("socketpair");
        exit(EXIT_FAILURE);
    }

    if (((pid = fork())) == -1)
    {
        perror("fork");
        exit(EXIT_FAILURE);
    }
    else if (pid == 0)
    { // 子进程
        close(sock[1]);
        for (i = 0; i < 10; i += 2)
        {
            sleep(1);
            sprintf(buf, "child,%d", i);
            write(sock[0], buf, sizeof(buf));
            read(sock[0], buf, sizeof(buf));
            printf("child receive form parent %s \n", buf);
        }
        close(sock[0]);
    }
    else
    { // 父进程
        close(sock[0]);
        for (i = 1; i < 10; i += 2)
        {
            sleep(1);
            sprintf(buf, "parent,%d", i);
            write(sock[1], buf, sizeof(buf));
            read(sock[1], buf, sizeof(buf));
            printf("parent receive form  child %s \n", buf);
        }
        close(sock[1]);
    }
    printf("helloworld\n");

    return 0;
}
